package com.example.ccj.b.c.custom.adapter;

import android.content.res.Resources;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.ccj.R;
import com.example.ccj.b.c.custom.LoadImageControlImageListener;
import com.example.ccj.b.c.custom.SelectPictureMode;
import com.example.ccj.u.ActivityUtils;
import com.example.ccj.u.ImageUtils;
import com.example.ccj.u.LogUtils;
import com.example.ccj.u.ToastUtils;
import com.example.ccj.u.media.IPictureSelectResultListener;
import com.example.ccj.u.media.MediaUtils;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.util.ArrayList;
import java.util.List;

/**
 * 图片展示Adapter 具备删除按钮
 * 2024年4月24日21:08:57
 */
public class LoadImageAdapter extends RecyclerView.Adapter<LoadImageAdapter.ViewHolder>{
    List<LocalMedia> pictureList;
    LoadImageControlImageListener loadImageControlImageListener;

    public boolean isCanDelete() {
        return isCanDelete;
    }

    public void setCanDelete(boolean canDelete) {
        isCanDelete = canDelete;
    }

    //是否可删除
    boolean isCanDelete;

    //最大选择数量
    int max = 10;

    SelectPictureMode mode = SelectPictureMode.picture;

    //是否可删除网资源
    boolean canDeleteNetWorkFile = true;

    /**
     *
     * @param pictureList  图片列表
     * @param isCanDelete  是否可删除图片
     * @param loadImageControlImageListener 事件回调，调用类需要处理添加事件，其他有默认的处理方式
     */
    public LoadImageAdapter(List<LocalMedia> pictureList, boolean isCanDelete, LoadImageControlImageListener loadImageControlImageListener){
        this.pictureList = pictureList;
        this.loadImageControlImageListener = loadImageControlImageListener;
        this.isCanDelete = isCanDelete;
    }

    public int getMax() {
        return max;
    }

    public void setMax(int num) {
        this.max = num;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(parent.getContext()).
                inflate(R.layout.adapter_load_picture, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        //加载添加图片布局
        if (isCanDelete && max > pictureList.size() && position == pictureList.size()) {
            holder.mIvDeleteImg.setVisibility(View.GONE);
            ImageUtils.loadImage(holder.itemView.getContext(),R.mipmap.load_img_add,holder.mIvLoadImg);
            //添加图片事件
            holder.mIvLoadImg.setOnClickListener(v -> {
                addImage();
            });

        } else {
            LocalMedia picture = pictureList.get(position);
            ImageUtils.loadImage(holder.itemView.getContext(),picture.getAvailablePath(),holder.mIvLoadImg);

            //图片大图展示
            bigImage(holder, position);

            //显示隐藏删除按钮
            if (isCanDelete) {
                //删除时判断你是否网络资源
                boolean hasHttp = PictureMimeType.isHasHttp(picture.getAvailablePath());
                if (hasHttp) {
                    if (canDeleteNetWorkFile) {
                        delete(holder, position);
                    } else {
                        holder.mIvDeleteImg.setVisibility(View.GONE);
                    }
                } else {
                    delete(holder, position);
                }
            } else holder.mIvDeleteImg.setVisibility(View.GONE);
        }
    }

    /**
     * 添加图片
     */
    public void addImage(){
        //添加图片逻辑
        loadImageMode(result -> {
            int addNum = 0;
            for (LocalMedia localMedia : result) {
                String availablePath = localMedia.getAvailablePath();
                if (picPath.contains(availablePath)) {
                    LogUtils.i("已存在的图片，不添加：" + availablePath);
//                    ToastUtils.showLong("已存在的图片，不添加：" + availablePath);
                } else {
                    picPath.add(availablePath);
                    pictureList.add(localMedia);
                    addNum ++;
                }
            }
            //刷新添加的数据
            if (pictureList.size() >= max) {
                notifyItemRangeInserted(pictureList.size()-addNum,addNum-1);
            } else {
                notifyItemRangeInserted(pictureList.size()-addNum,addNum);
            }
            notifyItemChanged(getItemCount()-1);
            LogUtils.i("选择："+result.size()+"  添加成功："+addNum);
//            if (!result.isEmpty()) ToastUtils.showLong("选择："+result.size()+"  添加成功："+addNum );
            if (loadImageControlImageListener != null) loadImageControlImageListener.onIncrease(result);
        });

    }

    /**
     * 大图展示
     * @param holder
     * @param position
     */
    private void bigImage(@NonNull ViewHolder holder, int position){
        //图片大图展示
        holder.mIvLoadImg.setOnClickListener(v -> {
            MediaUtils mediaUtils = new MediaUtils();
            mediaUtils.openPreview(ActivityUtils.getTopActivity(), position,false,new ArrayList<>(pictureList));
            if (loadImageControlImageListener != null) loadImageControlImageListener.onClick(pictureList.get(position),position);
        });
    }


    /**
     * 删除
     * @param holder
     * @param position
     */
    private void delete(@NonNull ViewHolder holder, int position){
        holder.mIvDeleteImg.setVisibility(View.VISIBLE);
        //删除图片事件
        holder.mIvDeleteImg.setOnClickListener(v->{
            LocalMedia remove = pictureList.remove(position);
            notifyItemRemoved(position);
            notifyItemRangeChanged(position,getItemCount()-1);
            picPath.remove(remove.getAvailablePath());
            if (loadImageControlImageListener != null) loadImageControlImageListener.onDelete(remove,position);
        });
    }

    public boolean isCanDeleteNetWorkFile() {
        return canDeleteNetWorkFile;
    }

    public void setCanDeleteNetWorkFile(boolean canDeleteNetWorkFile) {
        this.canDeleteNetWorkFile = canDeleteNetWorkFile;
    }

    List<String> picPath = new ArrayList<>();

    /**
     * 根据指定的模式加载图片
     * @param listener 回调
     */
    public void loadImageMode(IPictureSelectResultListener listener){
        MediaUtils mediaUtils = new MediaUtils();
        switch (mode) {
            case camera:
                mediaUtils.camera(ActivityUtils.getTopActivity(),listener);
                break;
            case picture:
                mediaUtils.pickAPicture(ActivityUtils.getTopActivity(),pictureList,listener);
                break;
            case PictureOrCamera:
                mediaUtils.pickAPictureOrCamera(ActivityUtils.getTopActivity(), pictureList, listener);
                break;
            case pickMultiplePicture:
                mediaUtils.pickMultiplePicture(ActivityUtils.getTopActivity(), pictureList,max, listener);
                break;
            case pickMultiplePictureOrCamera:
                mediaUtils.pickMultiplePictureOrCamera(ActivityUtils.getTopActivity(), pictureList,max, listener);
                break;
            case pickAMedia:
                mediaUtils.pickAMedia(ActivityUtils.getTopActivity(), pictureList, listener);
                break;
            case pickMultipleMedia:
                mediaUtils.pickMultipleMedia(ActivityUtils.getTopActivity(), pictureList,max, listener);
                break;
            case pickAAudio:
                mediaUtils.pickAAudio(ActivityUtils.getTopActivity(), pictureList, listener);
                break;
            case pickMultipleAudio:
                mediaUtils.pickMultipleAudio(ActivityUtils.getTopActivity(), pictureList,max, listener);
                break;
        }
    }


    public SelectPictureMode getMode() {
        return mode;
    }

    public void setMode(SelectPictureMode mode) {
        this.mode = mode;
    }

    @Override
    public int getItemCount() {
        if (isCanDelete)  {
            if (pictureList.size() < max) return pictureList.size() + 1;
            else return pictureList.size();
        }
        else return pictureList == null ? 0 : pictureList.size();
    }

    public static class ViewHolder extends  RecyclerView.ViewHolder{
        ImageView mIvLoadImg;
        ImageView mIvDeleteImg;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            mIvLoadImg = itemView.findViewById(R.id.adapter_load_image_img);
            mIvDeleteImg = itemView.findViewById(R.id.adapter_load_image_delete_img);
            /*
             * 设置水波纹背景
             */
            if (itemView.getBackground() == null) {
                TypedValue typedValue = new TypedValue();
                Resources.Theme theme = itemView.getContext().getTheme();
                int top = itemView.getPaddingTop();
                int bottom = itemView.getPaddingBottom();
                int left = itemView.getPaddingLeft();
                int right = itemView.getPaddingRight();
                if (theme.resolveAttribute(android.R.attr.selectableItemBackground, typedValue, true)) {
                    itemView.setBackgroundResource(typedValue.resourceId);
                }
                itemView.setPadding(left, top, right, bottom);
            }
        }
    }

}
